package com.dragon.web.commons.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dragon.common.utils.DateUtil;
import com.dragon.decision.entity.DecisionPointResult;
import com.dragon.loan.entity.CmAttachment;
import com.dragon.loan.service.CmAttachmentIDragonService;
import com.dragon.web.commons.constant.ErrorCode;
import com.dragon.web.commons.dto.GonganIdcardDTO;
import com.dragon.web.commons.utils.FileUtils;
import com.dragon.web.commons.utils.ImageUtils;
import com.dragon.web.commons.utils.UserUtils;
import com.fintech.common.entity.MaintenanceResult;
import com.fintech.common.enums.ReturnCode;
import com.fintech.common.util.MaintenanceUtils;
import com.fintech.common.vo.FintechResult;
import com.fintech.third.model.facerecog.FaceCompareResponse;
import com.fintech.third.service.facerecog.FaceRecognitionService;
import com.fintech.user.entity.RealNameAuthentication;
import com.fintech.user.entity.User;
import com.fintech.user.service.RealNameAuthenticationService;
import com.fintech.user.service.UserService;
import com.marvels.common.utils.MarvelsLogUtil;


@Controller
@RequestMapping("${platform.name.code}")
public class VerifyController {
	
	@Autowired
	private FaceRecognitionService faceRecognitionService;
	@Autowired
	private CmAttachmentIDragonService cmAttachmentService;
	@Autowired
	private RealNameAuthenticationService realNameAuthenticationService;
	@Autowired
	private UserService userService;
	/**
	 * 依图
	 */
	private static final String YITU = "0006";
	private static final String FACE = "0028";

	
	
	/**
	 * APP端识别客户证件时留存客户证件照片，通过身份证号、姓名、
	 * 证件照与公安信息中核查证件号姓名是否匹配，同时返回证件
	 * 照与公安库留存照片对比匹配度；返回校验结果是否通过。
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="online/idcard/{mobileNo}")
	public FintechResult onlineIdCard(@PathVariable String mobileNo ,@RequestBody GonganIdcardDTO gonganIdcardDTO ,HttpServletRequest request, @RequestHeader String accessToken, @RequestHeader String idFintechUmUser){
		String score = null;
		/**
		 * ADD BY TUXU 公安部系统升级，导致身份证验证及人脸比对无法使用，加挂一个提示
		 */
		MaintenanceResult result = MaintenanceUtils.getMaintenance("/resource.properties", "gongan");
		if (result.isMaintenance()) {
			return FintechResult.getFailResult(ErrorCode.FAIL, "服务维护升级中，请于" + result.getEndTime() + "后重试");
		}
		try {
			String pictureBase64 = gonganIdcardDTO.getPictureBase64();
//			AcLoanApplyInfo loan = loanInfoIDragonService.queryLoanBasicInfo(loanId);
			// 调用接口根据userId 来获取这个用户所对应的实名验证的信息
			User user = UserUtils.getUser(accessToken, idFintechUmUser);
			if (user == null) {
				return FintechResult.getResult(ReturnCode.tokenInvalid.getErrorCode(), "登录超时，请重新登录！", null);
			}
			Integer userId = user.getId();
			RealNameAuthentication realNameAuthentication = realNameAuthenticationService.queryByUserId(userId);
			if(null==realNameAuthentication){
				return FintechResult.getResult(ErrorCode.EXCEPTION, "未实名认证", null);
			}
			RealNameAuthentication tempEntity = new RealNameAuthentication();
			if(null!=realNameAuthentication.getFaceCheckTimes() && realNameAuthentication.getFaceCheckTimes()>=new Integer(FileUtils.getValueByPropertiesKey("face_times"))){
				SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd");
				Long diffDay = DateUtil.betweenDateWithDay(dfs.format(realNameAuthentication.getLastFaceCheckDate()), dfs.format(new Date()));
				if(diffDay<new Long(FileUtils.getValueByPropertiesKey("face_distance"))){
					return FintechResult.getResult("-10", "人脸识别次数太多", null);
				}
				realNameAuthentication.setFaceCheckTimes(0);
			}
			String loanId = mobileNo;
			 MarvelsLogUtil.getInstance().info("--------------------人脸识别入参数 ----  loanId = " + loanId);
			Map<String, String> params = new HashMap<>();
			params.put("idNumber", realNameAuthentication.getIdentityCardNo());
			params.put("userName", realNameAuthentication.getRealName());
			params.put("image_base64", pictureBase64);
			params.put("loanId", loanId);
			params.put("image_env", gonganIdcardDTO.getImage_env());
			params.put("channelCode", gonganIdcardDTO.getChannelCode());
			params.put("delta", gonganIdcardDTO.getDelta());
			params.put("productType", "1");//是否有产品，1无产品，2有产品
			// 人脸识别保存头像
			String prefix = FileUtils.getPathPrefix();
			String fileName = System.currentTimeMillis() + loanId;
			String pathPrefix = FileUtils.getValueByPropertiesKey("nfs.file.system");
			String path = pathPrefix + prefix;
			List<CmAttachment> cmAttachments = new ArrayList<CmAttachment>();
			File file = new File(path, fileName + "renlian.png");
			ImageUtils.base64ToImg(pictureBase64, file);
			
			 MarvelsLogUtil.getInstance().info("----------人脸识别上传照片完美通过----------" + loanId+",参数:"+gonganIdcardDTO.toString());
			
			FaceCompareResponse faceComparison = faceRecognitionService.faceComparison(params);
			//lgb 人脸识别认证结果
			DecisionPointResult dpr = new DecisionPointResult();
			dpr.setCustIdcard(realNameAuthentication.getIdentityCardNo());
			dpr.setFaceRecTime(new Date());
			
			
			tempEntity.setId(realNameAuthentication.getId());
			tempEntity.setLastFaceCheckDate(new Date());
			tempEntity.setFaceCheckTimes(realNameAuthentication.getFaceCheckTimes()==null?1:realNameAuthentication.getFaceCheckTimes()+1);
			realNameAuthenticationService.update(tempEntity);
			
			//人脸识别失败
			if(faceComparison == null && StringUtils.equals("1", FileUtils.getValueByPropertiesKey("face.error.handle"))) {
				//lgb 人脸识别认证结果
				dpr.setFaceRecTag("0");
				// decisionPointResultService.savePointResult(dpr);
				return FintechResult.getResult(ErrorCode.EXCEPTION, "人脸识别不通过", null);
			}
			
			if(faceComparison != null){
				score = faceComparison.getScore();
				String channelCode = faceComparison.getChannelCode();
				 MarvelsLogUtil.getInstance().info("----------score----------" + score);
				if(faceComparison.getErrorCode() == -10){
					 MarvelsLogUtil.getInstance().info("----------人脸识别次数太多----------" + loanId);
					/*loanInfoIDragonService.updateLoanStatus(loanId, "CR0");*/
					return FintechResult.getResult("-10", "人脸识别次数太多", null);
				}
				if(faceComparison.getErrorCode() == 0){
					if(score == null || "null".equalsIgnoreCase(score)){
						//lgb 人脸识别认证结果
						dpr.setFaceRecTag("0");
						// decisionPointResultService.savePointResult(dpr);
						return FintechResult.getResult(ErrorCode.EXCEPTION, "人脸识别不通过", null);
					}
					double doubleScorce = Double.parseDouble(score);
					if(YITU.equals(channelCode) || FACE.equals(channelCode)){
						doubleScorce = doubleScorce / 100;
					}
					 MarvelsLogUtil.getInstance().info("--------------------人脸识别入得分 ----  sorce = " + doubleScorce + "loanId" + loanId);
					if (doubleScorce < Double.parseDouble(FileUtils.getValueByPropertiesKey("renlian.score"))){
						//lgb 人脸识别认证结果
						dpr.setFaceRecTag("0");
						// decisionPointResultService.savePointResult(dpr);
						return FintechResult.getResult("-8", "人脸识别分数过低", null);
					} 
						
					CmAttachment cmAttachment = new CmAttachment();
					cmAttachment.setAtmtType("R");
					cmAttachment.setFileLocation(pathPrefix + prefix + "/" + fileName + "renlian.png");
					cmAttachment.setLoanId(loanId);
					cmAttachment.setUploadTime(new Date());
					cmAttachments.add(cmAttachment);
					cmAttachmentService.insertMsg(cmAttachments);
				} else {
					//lgb 人脸识别认证结果
					dpr.setFaceRecTag("0");
					// decisionPointResultService.savePointResult(dpr);
					return FintechResult.getResult(ErrorCode.EXCEPTION, "人脸识别不通过", null);
				}
			}else{
				//lgb 人脸识别认证结果
				dpr.setFaceRecTag("0");
				// decisionPointResultService.savePointResult(dpr);
				return FintechResult.getResult(ErrorCode.EXCEPTION, "人脸识别不通过", null);
			}
			//lgb 人脸识别认证成功 落库
			dpr.setFaceRecTag("1");
			// decisionPointResultService.savePointResult(dpr);
			
			tempEntity = new RealNameAuthentication();
			tempEntity.setId(realNameAuthentication.getId());
			tempEntity.setFaceTag("1");
			//人脸识别成功，失败次数重置为0
			tempEntity.setFaceCheckTimes(0);
			realNameAuthenticationService.update(tempEntity);
			
			MarvelsLogUtil.getInstance().info("开始更新人脸视别标识");
			User userParam = new User();
			userParam.setId(user.getId());
			userParam.setIdFintechUmUser(idFintechUmUser);
			userParam.setIsFace(1);
			userService.modifyUser(userParam);
		} catch (Exception e) {
			MarvelsLogUtil.getInstance().error("=====gongan/idcard/=====", e);
			return FintechResult.getResult(ErrorCode.FAIL, "系统异常", null);
		}
		return FintechResult.getResult(ErrorCode.SUCCESS, "操作成功", score);
	}

}
